package com.baibei.ebec.user.mine;

import android.content.Context;

import com.baibei.basic.BasicPresenterImpl;
import com.baibei.ebec.sdk.ApiFactory;
import com.baibei.ebec.sdk.IUserApi;
import com.baibei.model.BalanceInfo;
import com.baibei.model.MsgStatusInfo;
import com.baibei.model.PayModeInfo;
import com.baibei.model.UserInfo;
import com.baibei.sdk.ApiDefaultObserver;
import com.baibei.sdk.ApiException;
import com.baibei.sdk.Empty;
import com.blankj.utilcode.utils.LogUtils;
import com.rae.swift.session.SessionManager;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Function;

/**
 * Created by shenminjie on 2017/10/13.
 * mail:shenminjie@100bei.com
 */

public class MinePresenterImpl extends BasicPresenterImpl<MineContract.View> implements MineContract.Presenter {

    private IUserApi mUserApi;
    private PayModeInfo mModeInfo;
    private static final int MIN_WITHDRAW_AMOUNT = 2;
    private static final String CODE_NOT_ENOUGH_BALANCE_WITHDRAW = "CODE_NOT_ENOUGH_BALANCE_WITHDRAW";

    public MinePresenterImpl(Context context, MineContract.View view) {
        super(context, view);
        mUserApi = ApiFactory.getInstance().getUserApi();
    }

    @Override
    public void withdraw(final String password) {
        mView.showLoading();
//        提现金额需大于2元
        createObservable(mUserApi.getBalanceInfo()).flatMap(new Function<BalanceInfo, Observable<List<PayModeInfo>>>() {
            @Override
            public Observable<List<PayModeInfo>> apply(BalanceInfo info) throws Exception {
                //调试模式不需要判断金额大小
                if (info.getBalance() <= MIN_WITHDRAW_AMOUNT) {
                    throw new ApiException(CODE_NOT_ENOUGH_BALANCE_WITHDRAW, "提现金额需大于2元");
                }
                return createObservable(mUserApi.getPayModeList(2));
            }
        }).flatMap(new Function<List<PayModeInfo>, Observable<Empty>>() {
            @Override
            public Observable<Empty> apply(List<PayModeInfo> payModeInfos) throws Exception {
                //获取提现地址
                mModeInfo = (payModeInfos == null || payModeInfos.size() == 0) ? null : payModeInfos.get(0);
                return createObservable(mUserApi.fundVerifyPwd(password));
            }
        }).doFinally(new Action() {
            @Override
            public void run() throws Exception {
                if (mView != null) {
                    mView.hideLoading();
                }
            }
        }).subscribe(new ApiDefaultObserver<Empty>() {
            @Override
            protected void onError(String s) {
                if (mView != null) {
                    mView.onCheckFundFailed(s, false);
                }
            }

            @Override
            public void onError(ApiException e) {
                String msg = e.getMessage();
                //余额不足，不够提现
                if (mView != null && CODE_NOT_ENOUGH_BALANCE_WITHDRAW.equals(e.getCode())) {
                    mView.onNotEnoughWithDraw(msg);
                    return;
                }
                if (mView != null) {
                    mView.onCheckFundFailed(msg, "FUND_PWD_LOCK".equals(e.getCode()));
                }
            }

            @Override
            protected void accept(Empty empty) {
                if (mView != null) {
                    mView.onCheckFundSuccess(password, mModeInfo);
                }
            }
        });
    }

    @Override
    public void updateUserInfo() {
        createObservable(mUserApi.getUserInfo()).subscribe(new ApiDefaultObserver<UserInfo>() {
            @Override
            protected void onError(String s) {

            }

            @Override
            protected void accept(UserInfo userInfo) {
                //保存用户对象
                LogUtils.e("tag--收到指令，并更新用户信息，得到数据:" + userInfo);
                SessionManager.getDefault().setUser(userInfo);
                mView.onUpdateUserInfo(userInfo);
            }
        });
    }

    @Override
    public void getIfHasNewMsg(String userId, String accessToken) {
        createObservable(mUserApi.getIfHasNewMsg(userId,accessToken)).subscribe(new ApiDefaultObserver<List<MsgStatusInfo>>() {
            @Override
            protected void onError(String s) {
//                LogUtils.e("ifhasme",s);
            }

            @Override
            protected void accept(List<MsgStatusInfo> msgStatusInfos) {
//                LogUtils.e("ifhasm",msgStatusInfos.toString());
                mView.onSetMsgStatus(msgStatusInfos.get(0).getState());
            }
        });
    }
}
